/**
 * Mongoose 查询工具类
 * Created by benben on 14-9-19.
 */
var Page = require('../page/Page');

var Query = function(query){
    //实体类
    this.modle = query.modle;

};

/**
 * 分页数据
 *
 * @param model 实体类
 * @param conditions 条件
 * @param start
 * @param limit
 * @param callback
 */
Query.findPageWithModel = function(model,conditions,start,limit,callback){
    console.log(conditions);
    Query.queryWithConditions(model,conditions).count(function(err,count){
        Query.queryWithConditions(model,conditions).skip(start).limit(limit).exec(function(err,docs){
            if(err)
                callback(err);

            var page = new Page({
                totalCount : count,
                data : docs
            });
            callback(null,page);
        });
    });
};

Query.queryWithConditions = function(model,conditions){
    var query = model.find();
    if(conditions.items.length > 0){
        Query.convertConditions(query,conditions);
    }

    return query;
};

Query.convertConditions = function(query,conditions){
    var items = conditions.items;

    for(var i = 0; i < items.length; i++) {
        var item = items[i];
        if(item.type == 'like'){
            query.where(item.name).equals({ $regex:new RegExp(item.value)});
        }else if(item.type == 'in'){
            query.where(item.name).in(item.value)
        }else{
            query.where(item.name).equals(item.value);
        }
    }
};


module.exports = Query;